
import { getFullImageUrl, request } from '../../../utils/request';
export default {
  components: {},
  data() {
    return {
      recordList: [],
      total: 0,
      page: 1,
      limit: 10,
      loading: false,
      loadMoreStatus: 'more',
      statusOptions: ['全部', '待用户确认', '转账已受理', '转账锁定资金中', '转账中', '转账成功', '转账失败', '撤销中', '已撤销'],
      statusIndex: 0,
      startDate: '',
      endDate: '',
      stateMap: {
        'WAIT_USER_CONFIRM': '待用户确认',
        'ACCEPTED': '转账已受理',
        'PROCESSING': '转账锁定资金中',
        'TRANSFERING': '转账中',
        'SUCCESS': '转账成功',
        'FAIL': '转账失败',
        'CANCELING': '撤销中',
        'CANCELLED': '已撤销'
      },
      mchId: '', // 商户号，从后端获取
      appId: ''  // 应用ID，从后端获取
    };
  },
  onLoad() {
    this.fetchWithdrawalRecords();
  },
  methods: {
    getFullImageUrl,

    // 确认收款
    confirmPayment(item) {
      if (wx.canIUse('requestMerchantTransfer')) {
        wx.requestMerchantTransfer({
          mchId: this.mchId,
          appId: this.appId,
          package: item.package_info,
          success: (res) => {
            // res.err_msg将在页面展示成功后返回应用时返回ok，并不代表付款成功
            console.log('success:', res);
            uni.showToast({
              title: '收款请求已发送',
              icon: 'success'
            });
            // 调用确认收款接口
            this.confirmPayments(item.out_bill_no);
            // 刷新列表 - 添加延迟确保接口调用完成
            setTimeout(() => {
              console.log('执行刷新列表');
              this.fetchWithdrawalRecords();
            }, 1000);
          },
          fail: (res) => {
            console.log('fail:', res);
            uni.showToast({
              title: '收款请求失败',
              icon: 'none'
            });
            // 失败时也刷新列表
            setTimeout(() => {
              console.log('失败时执行刷新列表');
              this.fetchWithdrawalRecords();
            }, 1000);
          },
        });
      } else {
        wx.showModal({
          content: '你的微信版本过低，请更新至最新版本。',
          showCancel: false,
        });
      }
    },

    // 确认收款接口
    async confirmPayments(out_bill_no) {
      try {
        const res = await request({
          url: '/Withdrawals/confirmPayment',
          method: 'POST',
          data: {
            out_bill_no: out_bill_no
          }
        });
        if (res.code === 1) {
          uni.showToast({
            title: '确认收款成功',
            icon: 'success'
          });
        } else {
          uni.showToast({
            title: '确认收款失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('确认收款错误:', error);
        uni.showToast({
          title: '网络异常，请重试',
          icon: 'none'
        });
      }
    },

    // 获取提现记录
    async fetchWithdrawalRecords() {
      if (this.loading) return;

      this.loading = true;
      try {
        const params = {
          page: this.page,
          limit: this.limit
        };

        // 添加状态筛选
        if (this.statusIndex > 0) {
          const statusMap = ['', 'WAIT_USER_CONFIRM', 'ACCEPTED', 'PROCESSING', 'TRANSFERING', 'SUCCESS', 'FAIL', 'CANCELING', 'CANCELLED'];
          params.state = statusMap[this.statusIndex];
        }

        // 添加时间筛选
        if (this.startDate) {
          params.start_time = this.startDate;
        }
        if (this.endDate) {
          params.end_time = this.endDate;
        }

        const res = await request({
          url: '/Withdrawals/getWithdrawalLogList',
          method: 'GET',
          data: params
        });

        if (res.code === 1) {
          // 获取商户号和应用ID
          this.mchId = res.data.mch_id || '';
          this.appId = res.data.app_id || '';

          if (this.page === 1) {
            this.recordList = res.data.list;
          } else {
            this.recordList = [...this.recordList, ...res.data.list];
          }
          this.total = res.data.total;

          // 更新加载状态
          if (this.recordList.length >= this.total) {
            this.loadMoreStatus = 'noMore';
          } else {
            this.loadMoreStatus = 'more';
          }
        } else {
          uni.showToast({
            title: res.msg || '获取提现记录失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('获取提现记录错误:', error);
        uni.showToast({
          title: '网络异常，请重试',
          icon: 'none'
        });
      } finally {
        this.loading = false;
      }
    },

    // 加载更多
    loadMore() {
      if (this.loadMoreStatus === 'more' && !this.loading) {
        this.page++;
        this.fetchWithdrawalRecords();
      }
    },

    // 状态变化
    bindStatusChange(e) {
      this.statusIndex = e.detail.value;
      this.page = 1;
      this.fetchWithdrawalRecords();
    },

    // 开始日期变化
    bindStartDateChange(e) {
      this.startDate = e.detail.value;
      this.page = 1;
      this.fetchWithdrawalRecords();
    },

    // 结束日期变化
    bindEndDateChange(e) {
      this.endDate = e.detail.value;
      this.page = 1;
      this.fetchWithdrawalRecords();
    },

    // 重置筛选
    resetFilter() {
      this.statusIndex = 0;
      this.startDate = '';
      this.endDate = '';
      this.page = 1;
      this.fetchWithdrawalRecords();
    },

    // 获取状态文本
    getStatusText(state) {
      return this.stateMap[state] || '未知状态';
    },

    // 获取支付方式
    getPaymentMethod(item) {
      if (item.bank_account) {
        return '银行卡';
      } else if (item.alipay_account) {
        return '支付宝';
      } else if (item.wechat_account) {
        return '微信';
      } else {
        return '未知方式';
      }
    }
  }
}